package top.fengleifeng.question;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author : fengleifeng
 * @Package top.fengleifeng.question
 * @Description:
 * @date Date : 2020年12月15日 4:56 下午
 */
public class Num697数组的度 {

    class Solution {

        public int findShortestSubArray(int[] nums) {
            Map<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < nums.length; i++) {
                map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
            }
            //寻找数值做多的
            LinkedList<Integer> linkedList = new LinkedList<>();
            int max = -1;
            for (Entry<Integer, Integer> one : map.entrySet()) {
                int num = one.getValue();
                if (num > max) {
                    max = num;
                    linkedList.clear();
                    linkedList.add(one.getKey());
                } else if (num == max) {
                    linkedList.add(one.getKey());
                }
            }
            //每个数值的位置
            Map<Integer, LinkedList<Integer>> mapIndex = new HashMap<>();
            for (int i = 0; i < nums.length; i++) {
                if (linkedList.contains(nums[i])) {
                    LinkedList<Integer> now = mapIndex.getOrDefault(nums[i], new LinkedList<>());
                    now.add(i);
                    mapIndex.put(nums[i],now);
                }
            }
            int result = Integer.MAX_VALUE;
            //获取最小的度数
            for (Entry<Integer, LinkedList<Integer>> one : mapIndex.entrySet()) {
                LinkedList<Integer> list = one.getValue();
                Collections.sort(list);
                Integer first = list.getFirst();
                Integer last = list.getLast();
               int  nowResult = last-first +1;
               result = Math.min(nowResult,result);
            }
            return result;
        }
    }

    public static void main(String[] args) {
//        int[] ints = {1, 2, 2, 3, 1};
//        int[] ints = {1,2,2,3,1,4,2};
        int[] ints = {1,3,2,2,3,1};
        int shortestSubArray = new Num697数组的度().new Solution().findShortestSubArray(ints);

        System.out.println(shortestSubArray);
    }
}
